package com.example.emergencyattempt01.fragement.administrator_fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.administrator_activity.Add_User_Activity;
import com.example.emergencyattempt01.activity.utils.*;
import com.example.emergencyattempt01.adapter.Ad_RecordAdapter;
import com.example.emergencyattempt01.adapter.Person_ListView_Adapter;
import com.example.emergencyattempt01.adapter.Person_Manage_Pager_Adapter;
import com.example.emergencyattempt01.user.User;
import com.viewpagerindicator.TabPageIndicator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Person_Manage_Fragment extends Fragment {
    User administrator;
    TabPageIndicator personManageIndicator;
    ViewPager personManagePager;
    List<View> viewList=new ArrayList<>();
    Person_Manage_Pager_Adapter person_manage_pager_adapter;
    List<String> titleList=new ArrayList<>();

    View recordTab;
    View searchPersonTab;


    // 人员管理Tab
    TextView searchType;
    EditText searchField;
    ImageView addPerson;


    SwipeRefreshLayout searchPersonRefresh;

    ListView administrator_person_listView;
    List<Map<String,Object>> administrator_person_list=new ArrayList<>();
    Person_ListView_Adapter person_listView_adapter;
    Handler handlerForPerson_Search=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case UPDATE_PERSON_INFORMATION:
                    person_listView_adapter.notifyDataSetChanged();
                    break;
                case UPDATE_PERSON_INFORMATION_FAIL:
                    Toast.makeText(getActivity(),"网络错误！",Toast.LENGTH_SHORT).show();
                    break;
                case REFRESH_PERSON_INFORMATION:
                    person_listView_adapter.notifyDataSetChanged();
                    searchPersonRefresh.setRefreshing(false);
                    Toast.makeText(getActivity(),"已成功刷新列表！",Toast.LENGTH_SHORT).show();
                    break;
                case REFRESH_PERSON_INFORMATION_FAIL:
                    searchPersonRefresh.setRefreshing(false);
                    Toast.makeText(getActivity(),"网络错误！",Toast.LENGTH_SHORT).show();
                    break;
                case LOAD_SEARCH_INFORMATION:
                    person_listView_adapter.notifyDataSetChanged();
                    int n=(int)msg.obj;
                    Toast.makeText(getActivity(),"查询成功！共找到"+n+"条记录",Toast.LENGTH_LONG).show();
                    break;
                case LOAD_SEARCH_INFORMATION_FAIL:
                    Toast.makeText(getActivity(),"网络错误！",Toast.LENGTH_SHORT).show();
                    break;
                case  LOAD_SEARCH_INFORMATION_NOT_FOUND:
                    Toast.makeText(getActivity(),"未找到相关记录",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    final int UPDATE_PERSON_INFORMATION=0x002;
    final int UPDATE_PERSON_INFORMATION_FAIL=0x005;
    final int REFRESH_PERSON_INFORMATION=0x003;
    final int REFRESH_PERSON_INFORMATION_FAIL=0x006;
    final int LOAD_SEARCH_INFORMATION=0x004;
    final int LOAD_SEARCH_INFORMATION_FAIL=0x007;
    final int LOAD_SEARCH_INFORMATION_NOT_FOUND=0x008;


    // 借阅记录Tab
    ListView administrator_record_listView;
    List<Map<String,Object>> administrator_record_list=new ArrayList<>();
    Ad_RecordAdapter recordAdapter;
    Handler handlerForRecord=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case LOAD_RECORD_SUCCESS:
                    recordAdapter.notifyDataSetChanged();
                    canCount=true;
                    break;
                case LOAD_RECORD_NOT_FOUND:
                    Toast.makeText(recordTab.getContext(),"没有查到任何借阅信息",Toast.LENGTH_SHORT).show();
                    break;
                case LOAD_REORD_FAIL:
                    Toast.makeText(recordTab.getContext(),"网络出了些问题...",Toast.LENGTH_SHORT).show();
                    break;
                case RECORD_COUNT_DOWN:
                  recordAdapter.notifyDataSetChanged();
                    break;
                case RECORD_COUNT_ZERO:
                recordAdapter.notifyDataSetChanged();
                int i=(int)msg.obj;
                long outBid=(long)administrator_record_list.get(i).get("bid");
                    break;
            }
        }
    };
final int LOAD_RECORD_SUCCESS=0x021;
final int LOAD_RECORD_NOT_FOUND=0x025;

final int LOAD_REORD_FAIL=0x022;
final int RECORD_COUNT_DOWN=0x023;
final int RECORD_COUNT_ZERO=0x024;

boolean canCount=false;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.person_manage_layout,null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 设置基本构成
        setBasicPersonManage();
        // 设置找人tab
        setSearchPersonTab();
        // 设置借阅记录
        setRecord();
    }

    private void setRecord() {
        // 初始化
        initRecord();
        // 加载数据
        loadRecord();
    }


    private void loadRecord() {
        // 开辟线程，加载网络数据
      new Thread()
      {
          @Override
          public void run() {
              try {
                  canCount=false;
                  ServerMessage serverMessage=NetWorkUtils.getInstance().create(null,"/find_all_borrowing");
                  int code=serverMessage.getRespondCode();
                  if(code==200)
                  {
                      String fromServer=(String)serverMessage.getFromServer();
                      if(Pack_DePackUtil.dePackBorrowAhead(fromServer,administrator_record_list))
                      {
                          Message message=new Message();
                          message.what=LOAD_RECORD_SUCCESS;
                          handlerForRecord.sendMessage(message);
                      }
                      else
                      {
                          Message message=new Message();
                          message.what=LOAD_RECORD_NOT_FOUND;
                          handlerForRecord.sendMessage(message);
                      }
                  }
                  else
                  {
                      Message message=new Message();
                      message.what=LOAD_RECORD_SUCCESS;
                      handlerForRecord.sendMessage(message);
                  }
              }catch (JSONException e){e.printStackTrace();}
              catch (IOException e){e.printStackTrace();
                  Message message=new Message();
                  message.what=LOAD_RECORD_SUCCESS;
                  handlerForRecord.sendMessage(message);}
          }
      }.start();

      // 开辟线程，实现计时功能
        new Thread()
        {
            @Override
            public void run() {
                while(true)
                {
                    if(canCount)
                    {
                        try {
                            Thread.sleep(1000);
                        }catch (InterruptedException e){e.printStackTrace();}
                        for(int i=0;i<administrator_record_list.size();i++)
                        {
                            long last=(long)administrator_record_list.get(i).get("lastTime")-1000l;
                            if(last/1000>=0)// 描述大于零，不是毫秒数大于零
                            {
                                administrator_record_list.get(i).put("lastTime",last);
                                Message message=new Message();
                                message.what=RECORD_COUNT_DOWN;
                                handlerForRecord.sendMessage(message);
                            }
                            else
                            {
                                administrator_record_list.get(i).put("lastTime",0l);
                                Message message=new Message();
                                message.what=RECORD_COUNT_ZERO;
                                message.obj=i;
                                handlerForRecord.sendMessage(message);
                            }
                        }
                    }

                }
            }
        }.start();
    }

    private void initRecord() {
        administrator_record_listView=recordTab.findViewById(R.id.ad_record_listView);
        recordAdapter=new Ad_RecordAdapter(administrator_record_list,recordTab.getContext());
        administrator_record_listView.setAdapter(recordAdapter);
    }

    private void setBasicPersonManage() {
     personManageIndicator=getActivity().findViewById(R.id.person_manage_indicator);
     personManagePager=getActivity().findViewById(R.id.person_manage_pager);

     recordTab=LayoutInflater.from(getActivity()).inflate(R.layout.administrator_record_layout,null);
     searchPersonTab=LayoutInflater.from(getActivity()).inflate(R.layout.administrator_find_person_layout,null);

     viewList.add(searchPersonTab);
     viewList.add(recordTab);

     titleList.add("人员信息");
     titleList.add("借阅记录");
     // 为适配器进行初始化
     person_manage_pager_adapter=new Person_Manage_Pager_Adapter(getActivity(),viewList,titleList);
     // 建立适配器和viewPager，indicator的联系
        personManagePager.setAdapter(person_manage_pager_adapter);
        personManageIndicator.setViewPager(personManagePager);
    }

    private void setSearchPersonTab() {
        // 初始化listView
        administrator_person_listView=searchPersonTab.findViewById(R.id.search_listView);
        // 设置适配器
        person_listView_adapter=new Person_ListView_Adapter(administrator_person_list,searchPersonTab.getContext());
        administrator_person_listView.setAdapter(person_listView_adapter);

        // 加载初始时的请求：把所有学生都搬过来
        loadDefaultData();
        // 设置本页面的刷新逻辑
        setSearchPersonRefresh();
        // 设置加人逻辑
        setAddPerson();
        // 加入查找逻辑
        setSearchPerson();
    }

    private void setSearchPerson() {
        // 出弹窗，设置搜索类型
        setSearchType();
        // 发送查找请求，同时更新表格
        doSearch();

    }

    private void doSearch() {
        searchField=searchPersonTab.findViewById(R.id.find_person_search_edit);
        searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
               if(actionId== EditorInfo.IME_ACTION_SEARCH)
               {
                   new Thread(){
                       @Override
                       public void run() {
                           String keyWord=searchField.getText().toString().trim();
                           String type=searchType.getText().toString();
                           if(keyWord.equals(""))// 不许输入空
                           {
                               Toast.makeText(searchPersonTab.getContext(),"不许输入为空！",Toast.LENGTH_SHORT).show();
                           }
                           else
                           {
                               try
                               {
                                   // 打包数据，发给服务器
                                   JSONObject object=new JSONObject();
                                   object.put("keyWord",keyWord);
                                   object.put("searchType",type);

                                   String toServer=String.valueOf(object);
                                   ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/search_user");

                                   int code=serverMessage.getRespondCode();
                                   if(code==200)
                                   {
                                       // 清空本表
                                       administrator_person_list.clear();
                                       String fromServer=(String)serverMessage.getFromServer();
                                       JSONArray jsonArray=new JSONArray(fromServer);

                                       // 先查第一个object，看是否找到了
                                       JSONObject object1=jsonArray.getJSONObject(0);
                                       if(!object1.getBoolean("find"))// 未找到
                                       {
                                           Message message=new Message();
                                           message.what=LOAD_SEARCH_INFORMATION_NOT_FOUND;
                                           handlerForPerson_Search.sendMessage(message);
                                       }
                                       else // 找到了
                                       {
                                           Pack_DePackUtil.dePackUserInfo(jsonArray,administrator_person_list);
                                           Message message=new Message();
                                           message.obj=jsonArray.length();
                                           message.what=LOAD_SEARCH_INFORMATION;
                                           handlerForPerson_Search.sendMessage(message);
                                       }

                                   }
                                   else {
                                       Message message=new Message();
                                       message.what=LOAD_SEARCH_INFORMATION_FAIL;
                                       handlerForPerson_Search.sendMessage(message);
                                   }
                               }catch (JSONException e){e.printStackTrace();}
                               catch (IOException e){e.printStackTrace();
                                   Message message=new Message();
                                   message.what=LOAD_SEARCH_INFORMATION_FAIL;
                                   handlerForPerson_Search.sendMessage(message);}
                           }
                       }
                   }.start();
               }
              return false;
            }
        });
    }

    private void setSearchType() {
        searchType=searchPersonTab.findViewById(R.id.find_person_type);
        searchType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(searchPersonTab.getContext());
                View view=LayoutInflater.from(searchPersonTab.getContext()).inflate(R.layout.person_search_rule,null);
                TextView selectUid=view.findViewById(R.id.search_type_uid);
                TextView selectName=view.findViewById(R.id.search_type_userName);
                builder.setView(view);
                final AlertDialog dialog=builder.create();
                dialog.show();
                dialog.getWindow().setLayout(800,600);

                selectUid.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchType.setText("uid");
                        dialog.dismiss();
                    }
                });
                selectName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchType.setText("用户名");
                        dialog.dismiss();
                    }
                });

            }
        });
    }

    private void setAddPerson() {
     addPerson=searchPersonTab.findViewById(R.id.person_manage_add_person);

     addPerson.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             Intent intent = new Intent(getActivity(), Add_User_Activity.class);
             startActivity(intent);
         }
     });

    }

    private void setSearchPersonRefresh() {
        searchPersonRefresh=searchPersonTab.findViewById(R.id.find_person_refresh);
        searchPersonRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 再执行一次加载全部成员信息的工作，执行前，清空一下原表
                refreshFindPerson();

            }
        });
    }

    private void refreshFindPerson() {
        // 模拟数据产生/请求网络数据
        new Thread()
        {
            @Override
            public void run() {
                try
                {
                    //Person_info_test_resource test_resource=new Person_info_test_resource();
                    //String fromServer=test_resource.generateStringFromServer();
                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(null,"/query_all_user");
                    int code=serverMessage.getRespondCode();
                    if(code==200)
                    {
                        String fromServer=(String) serverMessage.getFromServer();
                        Pack_DePackUtil.dePackUserAhead(fromServer,administrator_person_list);
                        Message message=new Message();
                        message.what=REFRESH_PERSON_INFORMATION;
                        handlerForPerson_Search.sendMessage(message);
                    }
                    else {
                        Message message=new Message();
                        message.what=REFRESH_PERSON_INFORMATION_FAIL;
                        handlerForPerson_Search.sendMessage(message);
                    }

                }catch (JSONException e){e.printStackTrace();}
                catch (IOException e){e.printStackTrace();
                    Message message=new Message();
                    message.what=REFRESH_PERSON_INFORMATION_FAIL;
                    handlerForPerson_Search.sendMessage(message);}
            }
        }.start();
    }

    private void loadDefaultData() {
        // 模拟数据产生/请求网络数据
        new Thread()
        {
            @Override
            public void run() {
                try
                {
                    //Person_info_test_resource test_resource=new Person_info_test_resource();
                    //String fromServer=test_resource.generateStringFromServer();
                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(null,"/query_all_user");
                    int code=serverMessage.getRespondCode();
                    if(code==200)
                    {
                        String fromServer=(String) serverMessage.getFromServer();
                        Pack_DePackUtil.dePackUserAhead(fromServer,administrator_person_list);
                        Message message=new Message();
                        message.what=UPDATE_PERSON_INFORMATION;
                        handlerForPerson_Search.sendMessage(message);
                    }
                    else {
                        Message message=new Message();
                        message.what=UPDATE_PERSON_INFORMATION_FAIL;
                        handlerForPerson_Search.sendMessage(message);
                    }

                }catch (JSONException e){e.printStackTrace();}
                catch (IOException e){e.printStackTrace();
                    Message message=new Message();
                    message.what=UPDATE_PERSON_INFORMATION_FAIL;
                    handlerForPerson_Search.sendMessage(message);}

            }
        }.start();
    }
}
